ffmpeg将gif转换成mp4

参考文章
ffmpeg下载地址ffmpeg

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using UnityEngine;

public class Gifs2Mp4s {
    private static Gifs2Mp4s instance;
    public static Gifs2Mp4s Instance {
        get
        {
            if (instance == null) {
                instance = new Gifs2Mp4s();
            }
            return instance;
        }
    }
    private string gifsPath;
    private readonly string gifsDir = "/_ToolDataConfig/ToolTeachGuideConfig/Pics/";

    /// <summary>
    /// ffmpeg软件的位置
    /// </summary>
    //readonly string ffmpegPath = Application.streamingAssetsPath + "/ffmpeg/ffmpeg.exe";
    readonly string ffmpegPath = Application.dataPath.Replace("Assets" , "") +"ffmpeg/ffmpeg.exe";
    ProcessStartInfo info;
    readonly Thread t;
    /// <summary>
    /// gif文件转换成MP4文件
    /// 全部步骤完成之后杀掉所有的ffmpeg进程(建议手动调用KillFFMPEGProcess)
    /// </summary>
    /// <param name="ac">转换成功之后的回调</param>
    /// /// <param name="dirParh">gif文件夹路径</param>
    public void Gifs2MP4s(string dirParh = "" , Action ac = null) {
        string [] itemsPath;
        if (string.IsNullOrEmpty(dirParh)) {
            itemsPath = Directory.GetFiles(Application.streamingAssetsPath + gifsDir , "*.gif");
        }
        else {
            itemsPath = Directory.GetFiles(dirParh , "*.gif");
        }
        for (int i = 0 ; i < itemsPath.Length ; i++) {
            string itemPath = itemsPath [i];
            UnityEngine.Debug.Log($"gifPath:{itemPath}");
            GetMP4(itemPath);
        }
        ac?.Invoke();
    }
    private void GetMP4(string path) {
        if (string.IsNullOrEmpty(path)) return;
        gifsPath = Path.GetDirectoryName(path);
        string mp4Path = Path.Combine(gifsPath , Path.GetFileNameWithoutExtension(path) + ".mp4");
        UnityEngine.Debug.Log($"mp4Path:{mp4Path}");
        if (File.Exists(mp4Path)) {
            File.Delete(mp4Path);
        }
        info = new ProcessStartInfo(ffmpegPath);
        info.WindowStyle = ProcessWindowStyle.Hidden;
        info.CreateNoWindow = true;
        info.Arguments = $"-f gif -i {path} -pix_fmt yuv420p {mp4Path}";
        try {
            Process.Start(info);
            Thread.Sleep(20);
        }
        catch (System.Exception e) {
            UnityEngine.Debug.Log($"转换失败:{e.ToString()}");
        }
    }
    /// <summary>
    /// 生成之后手动调用,杀掉后台所有的ffmpeg进程
    /// </summary>
    public void KillFFMPEGProcess() {
        Process [] processes = Process.GetProcessesByName("ffmpeg");
        UnityEngine.Debug.Log("进程数:" + processes.Length);
        foreach (var item in processes) {
            item.Kill();
        }
    }
}
遇到宽或者高位奇数的加上:-vf "pad=ceil(iw/2)*2:ceil(ih/2)*2 "
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值